import Koa from 'koa'
import bodyparser from 'koa-bodyparser'
import Router from 'koa-router'
import cors from '@koa/cors'
import {Sequelize,Op,DataTypes} from 'sequelize'

let app=new Koa()
let router=new Router()
app.use(cors())
app.use(bodyparser())

//初始化sequelize实例
let sequelize=new Sequelize('bookDb','root','123456',{
    dialect:'mysql',
    host:'localhost'
})
//创建数据表
let Book=sequelize.define('books',{
    bookname:DataTypes.STRING,
    author:DataTypes.STRING
})
// 异步创建数据库数据表
await sequelize.sync()

// await Book.bulkCreate([
//     {
//         bookname:'歌谣',
//         author:'小麻'
//     },
//     {
//         bookname:'礼物',
//         author:'黄子弘凡'
//     },
//     {
//         bookname:'人鱼的眼泪',
//         author:'索尼'
//     },
//     {
//         bookname:'金鳞',
//         author:'黄子弘凡早安'
//     },
// ])

router.get('/book',async (ctx)=>{
    let keyword=ctx.request.query.keyword||''
    let where;
    if(keyword){
        where={
            [Op.or]:{
                bookname:{
                    [Op.like]:`%${keyword}%`
                },
                author:{
                    [Op.like]:`%${keyword}%`
                }
            }
        }
    }
    let books=await Book.findAll({where})
    ctx.body={
        code:1000,
        data:books
    }
})
router.get('/book/:id',async (ctx)=>{
    let id=ctx.params.id
    let book=await Book.findByPk(id)
    ctx.body={
        code:1000,
        data:book
    }
})
router.post('/book',async (ctx)=>{
    let obj=ctx.request.body
    let result=await Book.create(obj)
    ctx.body={
        code:1000,
        data:result
    }
})
router.put('/book/:id',async (ctx)=>{
    let id=ctx.params.id
    let obj=ctx.request.body
    let result=await Book.update(obj,{where:{id}})
    ctx.body={
        code:1000,
        data:result
    }
})
router.delete('/book/:id',async (ctx)=>{
    let id=ctx.params.id
    let result=await Book.destroy({where:{id}})
    ctx.body={
        code:1000,
        data:result
    }
})

app.use(router.routes())
app.listen(3080,()=>{console.log(`服务器运行于如下地址：http://localhost:3080`);
})